<?php
tsLoad('/core/CoreLib/AbstractMysqlPage.class.php');
class SysMemUserPage extends AbstractMysqlPage {
	/**
	 * 取得总的行数
     */
    protected function calTotalRows ()
    {
        global $mysqlTools;
        $condition = $mysqlTools->check_input($this->condition,array('userLoginId'));
        
       	$sqlCore = "
        	SELECT 
					count(DISTINCT su.userId) as totalCount
			FROM
					sys_user su left join sys_user_role sur on su.userId=sur.userId 
					left join sys_role sr on sur.roleId=sr.roleId
        ";
        
        $where = "
         	WHERE 1=1 and 
			sr.roleType=2
        ";
        
    	//用户信息查询
        if(!empty($condition['contact'])){
        	$where.= ' AND  (`su`.`userEmail` = '.$condition['contact'].
        	' OR `su`.`userTel` = '.$condition['contact'].
        	' OR `su`.`userPhone` = '.$condition['contact'].
        	' OR `su`.`userQQ` = '.$condition['contact'].' )';
        }
        
        //用户名查询
        if(!empty($condition['userLoginId'])){
        	$where.= ' AND  su.userLoginId LIKE '.$condition['userLoginId'];
        }
        
        //查看状态
        if(!empty($condition['userState']) && $condition['userState']!=5){
        	$where.= ' AND su.userState ='.$condition['userState'];
        }
        
        //创建开始时间与结束时间
        if(!empty($condition['userCreateTimeStart'])){
        	$where.= ' AND su.userCreateTime >='.$condition['userCreateTimeStart'];
        }
        if(!empty($condition['userCreateTimeEnd'])){
        	$where.= ' AND su.userCreateTime ='.$condition['userCreateTimeEnd'];
        }
        
        $sql = $sqlCore.$where;
        //总记录数
        $totalRows = $mysqlTools->selectSql($sql)[0]['totalCount'];
        
        return $totalRows;
    }

	/** 
     *取得数据集合
     */
    protected function getList ($sRowNo, $pageRows)
    {
        global $mysqlTools;
        
        //保存一个原生值以便需要的时候进行处理
        $orgCondition = $this->condition;
        
        $condition = $mysqlTools->check_input($this->condition,array('userLoginId'));
        
        $sqlCore = "
        	SELECT 
				DISTINCT su.userId, su.userLoginId ,su.userPhone,su.userTel,su.userSex,su.userCreateTime,
        		su.userRecom1LoginId,su.userRecom2LoginId,su.userRecom3LoginId,su.userState,
        		su.userIsCenterUser,su.userGold,sr.roleDesc
			FROM
				sys_user su left join sys_user_role sur on su.userId=sur.userId 
				left join sys_role sr on sur.roleId=sr.roleId
        ";
        
        $where = "
         	WHERE 1=1 and 
			sr.roleType=2
        ";
        
        //用户信息查询
        if(!empty($condition['contact'])){
        	$where.= ' AND  (`su`.`userEmail` = '.$condition['contact'].
        	' OR `su`.`userTel` = '.$condition['contact'].
        	' OR `su`.`userPhone` = '.$condition['contact'].
        	' OR `su`.`userQQ` = '.$condition['contact'].' )';
        }
        
        //用户名查询
        if(!empty($condition['userLoginId'])){
        	$where.= ' AND  su.userLoginId LIKE '.$condition['userLoginId'];
        }
        
        //查看状态
        if(!empty($condition['userState'])&& $condition['userState']!=5){
        	$where.= ' AND su.userState ='.$condition['userState'];
        }
        
        //创建开始时间与结束时间
        if(!empty($condition['userCreateTimeStart'])){
        	$where.= ' AND su.userCreateTime >='.$condition['userCreateTimeStart'];
        }
        if(!empty($condition['userCreateTimeEnd'])){
        	$where.= ' AND su.userCreateTime ='.$condition['userCreateTimeEnd'];
        }
        $order = "";
        if(!empty($orgCondition['order'])&&!empty($orgCondition['sort'])){
        	$order = " ORDER BY su.".$orgCondition['sort']." ".$orgCondition['order']." ";
        }else{
	        $order = " ORDER BY `su`.`userCreateTime` DESC ";
        }
        $limit = " LIMIT $sRowNo,$pageRows";
        $sql = $sqlCore.$where.$order.$limit;
        
        //查询角色信息分页
        $list = $mysqlTools->selectSql($sql);
        
        return $list;
    }
    
    /**
     *取得数据集合
     */
    public function queryMoneySum ($condition)
    {
    	global $mysqlTools;
    
    	//保存一个原生值以便需要的时候进行处理
    	$orgCondition = $condition;
    
    	$condition = $mysqlTools->check_input($condition,array('userLoginId'));
    
    	$sqlCore = "
        	SELECT
				sum(su.userGold) moneySum
			FROM
				sys_user su left join sys_user_role sur on su.userId=sur.userId
				left join sys_role sr on sur.roleId=sr.roleId
        ";
    
    	$where = "
         	WHERE 1=1 and
			sr.roleType=2
        ";
    
    	//用户信息查询
    	if(!empty($condition['contact'])){
    		$where.= ' AND  (`su`.`userEmail` = '.$condition['contact'].
    		' OR `su`.`userTel` = '.$condition['contact'].
    		' OR `su`.`userPhone` = '.$condition['contact'].
    		' OR `su`.`userQQ` = '.$condition['contact'].' )';
    	}
    
    	//用户名查询
    	if(!empty($condition['userLoginId'])){
    		$where.= ' AND  su.userLoginId LIKE '.$condition['userLoginId'];
    	}
    
    	//查看状态
    	if(!empty($condition['userState'])&& $condition['userState']!=5){
    		$where.= ' AND su.userState ='.$condition['userState'];
    	}
    
    	//创建开始时间与结束时间
    	if(!empty($condition['userCreateTimeStart'])){
    		$where.= ' AND su.userCreateTime >='.$condition['userCreateTimeStart'];
    	}
    	if(!empty($condition['userCreateTimeEnd'])){
    		$where.= ' AND su.userCreateTime ='.$condition['userCreateTimeEnd'];
    	}
    	$sql = $sqlCore.$where;
    	//查询角色信息分页
    	$list = $mysqlTools->selectSql($sql);
    	if (is_array ( $list ) && ! empty ( $list ))
    		return $list[0];
    	else
    		return array();
    }
    
    /**
     *通过loginId查询用户是否存在
     */
    public function getUserByLoginId ($condition)
    {
    	global $mysqlTools;
    
    	$condition = $mysqlTools->check_input($condition);
    
    	$sql = "
    	SELECT
    	su.userId,
    	su.userLoginId,
    	su.userPwd,
    	su.userPhone,
    	su.userTel,
    	su.userEmail,
    	su.userQQ,
    	su.userAvatarId,
    	su.userState,
    	su.userCreateTime,
    	su.userSex
    	FROM
    	sys_user su 
    	where
    	su.userLoginId = $condition[userLoginId]
    	";
    
    	//查询用户信息
    	$list = $mysqlTools->selectSql($sql);
    	if(!empty($list))
    		return $list[0];
    	else
    		return array();
    }
    
    /**
     *取得用户信息
     */
    public function getUserById ($condition)
    {
    	global $mysqlTools;
    
    	$condition = $mysqlTools->check_input($condition);
    
    	$sql = "
        	SELECT
				su.userId,
				su.userLoginId,
				su.userPwd,
				su.userPhone,
				su.userTel,
				su.userEmail,
				su.userQQ,
				su.userAvatarId,
				su.userState,
				su.userCreateTime,
				su.userSex,
				sp.photoUrl,
				sp.photoNoExtUrl,
				sp.photoExt
			FROM
				sys_user su left join sys_photo sp on su.userAvatarId=sp.photoId
			where 
				su.userId = $condition[userId]
        ";
    
    	//查询用户信息
    	$list = $mysqlTools->selectSql($sql);
    	if(!empty($list))
    		return $list[0];
    	else
    	 	return array();
    }
    
    /**
     *取得用户角色信息
     */
    public function getUserRoleById ($condition)
    {
    	global $mysqlTools;
    
    	$condition = $mysqlTools->check_input($v);
    
    	$sql = "
        	select  `sr`.`name` as `roleName` FROM `sys_role` `sr`
		        INNER JOIN
		    `sys_user_role` `sur` ON `sur`.`roleId` = `sr`.`id`
    		WHERE `sur`.`userId` = $v->get[userId]
        ";
    
    	//查询用户信息
    	$list = $mysqlTools->selectSql($sql);
    	if(!empty($list))
    		return $list;
    	else
    		return array();
    }
    
    //增加一个用户
    public function addUser($condition){
    	global $mysqlTools;
    	//生成唯一ID
    	$uniqid = getCurrentId();
    
    	$condition['userPwd'] = md5($condition['userPwd']);
    	
    	//参数处理注入SQL安全问题
    	$condition = $mysqlTools->check_input($condition);
    	//处理null值,如果值为null数据库也置为null
    	$condition = $mysqlTools->check_null($condition);
    	try {
    		$mysqlTools->startTransaction();
    		$result = $mysqlTools->executeSql("
    				insert into sys_user (userId,userLoginId,userPwd,userPhone,userTel,userQQ,userEmail,userAvatarId,userState,userSex,userCreateTime)
    				values($uniqid,$condition[userLoginId],$condition[userPwd],$condition[userPhone],$condition[userTel],$condition[userQQ],$condition[userEmail],
    				$condition[userAvatarId],1,$condition[userSex],now())
    				");
    		$mysqlTools->commitTransaction();
    	} catch (\Exception $e) {
    		$mysqlTools->rollback();
    	}
    	return $result;
    }
    
    /**
	 * 添加一个用户角色信息
	 */
	public function addUserRoles($condition){
		global $mysqlTools;
			
		//参数处理注入SQL安全问题
		//$condition = $mysqlTools->check_input($condition);
		try {
			$mysqlTools->startTransaction();
			//首先删除以前的该用户角色
			$result = $mysqlTools->executeSql("
					delete from sys_user_role where userId = $condition[userId];
					");
			//取出角色菜单数组后进行循环插入
			if(!empty($condition['userRoleIds'])){
				$roleIds = explode(",",$condition['userRoleIds']);
				foreach ($roleIds as $roleId) {
					if(is_numeric($roleId)){
						$result = $result&&$mysqlTools->executeSql("insert into sys_user_role(userId,roleId) values($condition[userId],$roleId);");
					}
				}
			}
	
			if($result)
				$mysqlTools->commitTransaction();
			else
				$mysqlTools->rollback();
		} catch (\Exception $e) {
			$mysqlTools->rollback();
			return "数据库插入发生异常";
		}
		return $result;
	}
    
    /**
     * 删除用户菜单
     */
    public function delUserMenu($condition){
    	global $mysqlTools;
    	//参数处理注入SQL安全问题
    	$result = true;
    	if(array_key_exists('del',$condition) && empty($condition['del'])){
    		return $result;
    	}
    	$list = explode(',',$condition['del']);
    	$condition = $mysqlTools->check_input($condition);
    	if(!empty($condition['del'])){
    		foreach ($list as $menuId){
    			$res = $mysqlTools->executeSql("
    					DELETE FROM `sys_user_menu`
    					WHERE `menuId` = $menuId AND `userId` = $condition[userId]
    					");
    			if(!$res){
    				$result = false;
    			}
    		}
    	}
    	return $result;
    }
    
    /**
     * 修改用户
     */
    public function updateUser($condition){
    	global $mysqlTools;
    	//参数处理注入SQL安全问题
    	if(!empty($condition['userPwd']))
    		$pwd = $condition['userPwd'];
    	$condition = $mysqlTools->check_input($condition);
    	try {
    		$sql = "UPDATE `sys_user` SET `userId` = `userId`";
    		if(!empty($condition['userLoginId'])){
           		$sql.= ",`userLoginId` = $condition[userLoginId]";
    		}
    		if(!empty($pwd)){
    			$pwd = md5($pwd);
    			$sql.= ",`userPwd` = '$pwd'";
    		}
    		if(!empty($condition['userPhone'])){
    			$sql.= ",`userPhone` = $condition[userPhone]";
    		}
    		if(!empty($condition['userSex'])){
    			$sql.= ",`userSex` = $condition[userSex]";
    		}
    		if(!empty($condition['userTel'])){
    			$sql.= ",`userTel` = $condition[userTel]";
    		}
    		if(!empty($condition['userEmail'])){
    			$sql.= ",`userEmail` = $condition[userEmail]";
    		}
    		if(!empty($condition['userQQ'])){
    			$sql.= ",`userQQ` = $condition[userQQ]";
    		}
    		if(!empty($condition['userAvatarId'])){
    			$sql.= ",`userAvatarId` = $condition[userAvatarId]";
    		}
    		if(isset($condition['userState'])){
    			$sql.= ",`userState` = $condition[userState]";
    		}
    		$sql.=" where `userId` = $condition[userId]";
    		$mysqlTools->startTransaction();
    		$result = $mysqlTools->executeSql($sql);
    		$mysqlTools->commitTransaction();
    	} catch (\Exception $e) {
    		$mysqlTools->rollback();
    	}
    	return $result;
    }
    
    /**
     * 查询名称是否存在
     */
    public function checkUserName($condition){
    	global $mysqlTools;
    	//参数处理注入SQL安全问题
    	$condition = $mysqlTools->check_input($condition);
    	try {
    		$mysqlTools->startTransaction();
    		$sql = 'SELECT COUNT(*) as count FROM `sys_user` ';
    		$sql.= ' WHERE `userLoginId` = '.$condition['userLoginId'];
    		if(!empty($condition['userId'])){
    			$sql.=' AND `userId` <> '.$condition['userId'];
    		}
    		$result = $mysqlTools->selectSql($sql)[0]['count'];
    		$mysqlTools->commitTransaction();
    	} catch (\Exception $e) {
    		$mysqlTools->rollback();
    		return false;
    	}
    	return $result==0;
    }
    
    /**
     * 处理菜单操作
     */
    public function processUserMenus($condition)
    {
    	global $mysqlTools;
    	try {
	    	$mysqlTools->startTransaction();
	    	$result = $this->addUserMenu($condition) && $this->delUserMenu($condition);
	    	if($result){
	    		$mysqlTools->commitTransaction();
	    	}else{
	    		$mysqlTools->rollback();
	    	}
    	} catch (\Exception $e) {
    		$mysqlTools->rollback();
    		return $result;
    	}
    	return $result;
    }
    
    /**
     * 为用户充值
     */
    public function userRechange($condition){
    	//检查session里的用户必须角色是财务才可以操作
    	global $mysqlTools;
    	
    	try{
	    	$mysqlTools->startTransaction();
	    	//根据用户id查询用户角色信息
	    	$queryUserRoleSql = "
	    		SELECT
					sr.roleName
				FROM
					sys_user su
				LEFT JOIN sys_user_role sur ON su.userId = sur.userId
				LEFT JOIN sys_role sr ON sur.roleId = sr.roleId
				where 
					su.userId=$condition[myUserId]
	    	";
	    	$userRoleInfo = $mysqlTools->selectSql($queryUserRoleSql)[0];
	    	
	    	if($userRoleInfo['roleName']=='finance' || $userRoleInfo['roleName']=='manage'){
	    		//根据输入的金额进行增加用户金钱
	    		$addUserGoldSql = "
	    			update sys_user set userGold = userGold+$condition[rechangeGold] where userId=$condition[userId]		
	    		";
	    		$result = $mysqlTools->executeSql($addUserGoldSql);
	    		
	    		//通过userId查询loginId
	    		$queryUserInfoSql = "
	    			SELECT
						su.userLoginId,
						sr.roleId,
						sr.roleDesc,
						su.userGold
					FROM
						sys_user su
						LEFT JOIN sys_user_role sur ON su.userId = sur.userId
						LEFT JOIN sys_role sr ON sur.roleId = sr.roleId
					WHERE
						su.userId = $condition[userId]		
	    		";
	    		
	    		//为系统生成收益记录
	    		$profitInfoId = getCurrentId();
	    		$insertSysProfitInfo = "
	    			insert into	sys_profit_info(sysProInId,sysProInCreatetime,sysProInReason,sysProInMo)
	    			values($profitInfoId,now(),5,0)
	    		";
	    		$mysqlTools->executeSql($insertSysProfitInfo);
	    		
	    		//生成唯一ID
	    		$uniqid = getCurrentId();
	    		$queryUserInfo = $mysqlTools->selectSql($queryUserInfoSql)[0];
	    		//为用户记录交易日志
	    		$insertUserBopInfoSql = "
	    			insert into user_bop_info(userInFId,userInFZf,userInFUserId,userInFLoginId,userInFCreatetime,userInFType,
	    				userInFMo,roleId,roleDesc,userInFOthMo,userInFReason,userInFReId,withdId,sysProInId,userInFSurGlod)
	    			values ($uniqid,1,$condition[userId],'$queryUserInfo[userLoginId]',now(),6,$condition[rechangeGold],
	    			$queryUserInfo[roleId],'$queryUserInfo[roleDesc]',0,11,0,0,$profitInfoId,$queryUserInfo[userGold])	
	    		";
	    		
	    		$mysqlTools->executeSql($insertUserBopInfoSql);
	    		
	    		
	    		
	    	}else{
	    		$mysqlTools->rollback();
	    		return false;
	    	}
	    	$mysqlTools->commitTransaction();
	    	return true;
    	}catch (\Exception $e){
    		$mysqlTools->rollback();
    		return false;
    	}
    	
    }
    
    /**
     * 财务把一个用户升级为普通会员
     */
    public function updateUserToMem($condition)
    {
    	global $mysqlTools;
    	try {
    		tsLoad('/manage/busi/UserBusi.class.php');
    		$mysqlTools->startTransaction();
    		$userId = $condition['userId'];
    		$condition = $mysqlTools->check_input($condition);
    		//把一个用户改成激活状态变成了普通会员
    		$coreSql = "
    			update sys_user set userState=1,userGold=userGold+1000 where userId = $condition[userId] 		
    		";
    		
    		//查询用户分层情况
    		$queryUser = "
    			SELECT
					su.userId,
					su.userLoginId,
					su.userPwd,
					su.userPhone,
					su.userTel,
					su.userEmail,
					su.userQQ,
					su.userAvatarId,
					su.userState,
					su.userShortIndex,
					su.userIndex,
					su.userCreateTime,
					su.userSex,
					su.userPassTime,
					su.userRecom1UserId,
					su.userRecom1LoginId,
					su.userRecom2UserId,
					su.userRecom2LoginId,
					su.userRecom3UserId,
					su.userRecom3LoginId,
					su.userIsCenterUser,
					su.userPassType,
					su.userGold,
					su.userMainPassUserId,
					su.userMainPassLoginId,
					su.userCenterUserId,
					su.userCenterLoginId,
					sr.roleId,
					sr.roleDesc
				from
					sys_user su left join sys_user_role sur on su.userId=sur.userId 
					left join sys_role sr on sur.roleId=sr.roleId
				where 
					su.userId = $condition[userId]
    		";
    		//取出1，2，3级推荐人
    		$userSelf = $mysqlTools->selectSql($queryUser)[0];
    		//划分累积的奖金
    		$accuMo = 0;
			//系统收益ID要提前生成起以便于关联查询
    		$sysProInId = getCurrentId();
    		//为系统生成用户收入起始1000野猪币日志
    		$this->insertUserBopInfo($userSelf, 1000, $sysProInId);
			//先添加日志后增加实际的钱
    		$mysqlTools->executeSql($coreSql);
    		
    		
    		
    		if(isset($userSelf)){
    			$userRecom1UserId = $userSelf['userRecom1UserId'];
    			$userRecom2UserId = $userSelf['userRecom2UserId'];
    			$userRecom3UserId = $userSelf['userRecom3UserId'];
    			//根据用户角色计算用户获得奖金
    			if(isset($userRecom1UserId))
    				$accuMo = $accuMo + $this->userBonus($userRecom1UserId, 1, 1000, 1,$sysProInId);
    			if(isset($userRecom2UserId))
    				$accuMo = $accuMo + $this->userBonus($userRecom2UserId, 2, 1000, 1,$sysProInId);
    			if(isset($userRecom3UserId))
    				$accuMo = $accuMo + $this->userBonus($userRecom3UserId, 3, 1000, 1,$sysProInId);
    		}
    		//为系统记录收入日志
    		$userInFId = getCurrentId();
    		//查看是否有报单用户,有报单用户将多获得50元的现金
    		if(isset($userSelf['userCenterUserId'])){
    			//计算操作后我的野猪币数量为
    			$queryMyGlodSql = "
    				SELECT
						su.userGold,
						sr.roleId,
						sr.roleDesc
					FROM
						sys_user su
					LEFT JOIN sys_user_role sur ON su.userId = sur.userId
					left join sys_role sr on sur.roleId=sr.roleId
					WHERE
						su.userId = $userSelf[userCenterUserId]
					limit 0,1
    			";
    			$centerUserInfo = $mysqlTools->selectSql($queryMyGlodSql)[0];
    			$surGlod = $centerUserInfo['userGold']+50;
    			$centerUserMoSql = "
    				insert into user_bop_info(userInFId,userInFUserId,userInFLoginId,userInFCreatetime,
	    			userInFType,userInFMo,roleId,roleDesc,userInFOthMo,userInFReason,sysProInId,userInFSurGlod,userInFZf) values 
	    			($userInFId,$userSelf[userCenterUserId],'$userSelf[userCenterLoginId]',now(),4,50,$centerUserInfo[roleId],
	    			'$centerUserInfo[roleDesc]'
	    			,0,4,$sysProInId,$surGlod,1)		
    			";
    			$mysqlTools->executeSql($centerUserMoSql);
    			
    			$addCenterUserMoSql = "
    				update sys_user set userGold=userGold+50 where userId=$userSelf[userCenterUserId]
    			";
    			$mysqlTools->executeSql($addCenterUserMoSql);
    			$accuMo = $accuMo+50;
    		}
    		
    		//为指定收益人给予系统指定的提成
    		//查询出收益人userId
    		$queryIncomeUserId = "
    			select sysBenUserId from sys_set limit 0,1		
    		";
    		$incomeUserId = $mysqlTools->selectSql($queryIncomeUserId)[0]['sysBenUserId'];
    		$accuMo = $accuMo + $this->userBonus($incomeUserId, 5, 1000, 5,$sysProInId);
    		
    		$sysProInMo = 1000-$accuMo;
    		
    		//拿出10%给前10级推荐人
    		//查询关联的10个用户信息
    		$lossMo = $this->tenRecomUserOnePercent($userId, 10, $sysProInId);
    	    $sysProInMo = $sysProInMo-$lossMo;
    		
    		$sysIncomeLogSql = "
    			insert into sys_profit_info (sysProInId,sysProInCreatetime,sysProInReason,sysProInMo)
    			values ($sysProInId,now(),1,$sysProInMo);
    		";
    		$mysqlTools->executeSql($sysIncomeLogSql);
    		
    		$result=true;
    		if($result){
    			$mysqlTools->commitTransaction();
    		}else{
    			$mysqlTools->rollback();
    		}
    	} catch (\Exception $e) {
    		$mysqlTools->rollback();
    		return $result;
    	}
    	return $result;
    }
    
    /**
     * 根据用户ID和推荐等级计算一个用户在推荐到人的时候应该得到的野猪币数量
     */
    public function userBonus($userId,$recomLevel,$tradeMo,$userInFReason,$sysProInId){
    	global $mysqlTools;
    	
    	try {
	    	$mysqlTools->startTransaction();
	    	
	    	$queryUserRoleSql = "
	    		SELECT
					sr.roleLevel,
					sr.roleId,
					sr.roleDesc
				FROM
					sys_user_role sur
				LEFT JOIN sys_role sr ON sur.roleId = sr.roleId
				WHERE
					sur.userId = $userId
				LIMIT 0,1 
	    	";
	    	
	    	//根据角色等级计算额外佣金并且返佣
	    	$role = $mysqlTools->selectSql($queryUserRoleSql)[0];
	    	//根据userId查询用户信息
	    	$queryUserInfoByUserIdSql = "
	    		SELECT
				su.userId,
				su.userLoginId
				from sys_user su
				where su.userId = $userId
	    	";
	    	$userInfo = $mysqlTools->selectSql($queryUserInfoByUserIdSql)[0];
	    	
	    	$addMo = 0;
	    	if(isset($role) && $recomLevel<=3){
	    		$addMo = $tradeMo*($role['roleLevel']-1)/100;
	    	}
	    	
	    	switch ($recomLevel){
	    		case 1:
	    			$normalMo = $tradeMo*0.15;
	    			break;
	    		case 2:
	    			$normalMo = $tradeMo*0.10;
	    			break;
	    		case 3:
	    			$normalMo = $tradeMo*0.08;
	    			break;
	    		default:
	    			$querySysProfitRate = "
		    			select sysBenPer from sys_set limit 0,1
		    		";
	    			$sysBenPer = $mysqlTools->selectSql($querySysProfitRate)[0]['sysBenPer'];
	    			//指定收益人获得系统指定分层
	    			$normalMo = $tradeMo*($sysBenPer/100);
	    			break;
	    	}
	    	
	    	$userInFMo = $normalMo+$addMo;
	    	//生成唯一ID
	    	$uniqid = getCurrentId();
	    	//计算操作后我的野猪币数量为
	    	$queryMyGlodSql = "
	    		select userGold from sys_user where userId=$userId		
	    	";
	    	$surGlod = $mysqlTools->selectSql($queryMyGlodSql)[0]['userGold']+$userInFMo;
	    	$addIncomeDetail = "insert into user_bop_info(userInFId,userInFUserId,userInFLoginId,userInFCreatetime,
	    			userInFType,userInFMo,roleId,roleDesc,userInFOthMo,userInFReason,sysProInId,userInFZf,userInFSurGlod) values 
	    			($uniqid,$userId,'$userInfo[userLoginId]',now(),$recomLevel,$userInFMo,$role[roleId],'$role[roleDesc]'
	    			,$addMo,$userInFReason,$sysProInId,1,$surGlod)
	    	";
	    	$mysqlTools->executeSql($addIncomeDetail);
	    	//为相应人员加钱
	    	if(isset($userInFMo) && $userInFMo>0){
		    	$addUserMoSql = "
		    		update sys_user set userGold=userGold+$userInFMo where userId=$userId		
		    	";
		    	$mysqlTools->executeSql($addUserMoSql);
	    	}
	    	
	    	return $userInFMo;
    	} catch (\Exception $e) {
    		$mysqlTools->rollback();
    		return 0;
    	}
    }
    
    /**
     * 财务把一个用户从未激活升级到报单用户
     */
    public function updateUserToCenter($condition)
    {
    	global $mysqlTools;
    	try {
    		tsLoad('/manage/busi/UserBusi.class.php');
    		$mysqlTools->startTransaction();
    		$userId = $condition['userId'];
    		$condition = $mysqlTools->check_input($condition);
    		
    		//把一个用户改成激活状态变成了普通会员
    		$coreSql = "
    			update sys_user set userState=1,userGold=userGold+1000,userIsCenterUser=1 where userId = $condition[userId] 		
    		";
    		
    		//查询用户分层情况
    		$queryUser = "
    			SELECT
					su.userId,
					su.userLoginId,
					su.userPwd,
					su.userPhone,
					su.userTel,
					su.userEmail,
					su.userQQ,
					su.userAvatarId,
					su.userState,
					su.userShortIndex,
					su.userIndex,
					su.userCreateTime,
					su.userSex,
					su.userPassTime,
					su.userRecom1UserId,
					su.userRecom1LoginId,
					su.userRecom2UserId,
					su.userRecom2LoginId,
					su.userRecom3UserId,
					su.userRecom3LoginId,
					su.userIsCenterUser,
					su.userPassType,
					su.userGold,
					su.userMainPassUserId,
					su.userMainPassLoginId,
					su.userCenterUserId,
					su.userCenterLoginId,
		    		sr.roleId,
					sr.roleDesc
				from
					sys_user su left join sys_user_role sur on su.userId=sur.userId 
					left join sys_role sr on sur.roleId=sr.roleId
				where 
					su.userId = $condition[userId]
    		";
    		//取出1，2，3级推荐人
    		$userSelf = $mysqlTools->selectSql($queryUser)[0];
    		//划分累积的奖金
    		$accuMo = 0;
    		//系统收益ID要提前生成起以便于关联查询
    		$sysProInId = getCurrentId();
    		//为系统生成用户收入起始1000野猪币日志
    		$this->insertUserBopInfo($userSelf, 1000, $sysProInId);
    		//增加日志后在增加钱
    		$mysqlTools->executeSql($coreSql);
    		
    		if(isset($userSelf)){
    			$userRecom1UserId = $userSelf['userRecom1UserId'];
    			$userRecom2UserId = $userSelf['userRecom2UserId'];
    			$userRecom3UserId = $userSelf['userRecom3UserId'];
    			//根据用户角色计算用户获得奖金
    			if(isset($userRecom1UserId))
    				$accuMo = $accuMo + $this->userBonus($userRecom1UserId, 1, 10000, 1,$sysProInId);
    			if(isset($userRecom2UserId))
    				$accuMo = $accuMo + $this->userBonus($userRecom2UserId, 2, 10000, 1,$sysProInId);
    			if(isset($userRecom3UserId))
    				$accuMo = $accuMo + $this->userBonus($userRecom3UserId, 3, 10000, 1,$sysProInId);
    		}
    		//为系统记录收入日志
    		$userInFId = getCurrentId();
    		//查看是否有报单用户,有报单用户将多获得500元的现金
    		if(isset($userSelf['userCenterUserId'])){
    			//计算操作后我的野猪币数量为
    			$queryMyGlodSql = "
    			SELECT
    			su.userGold,
    			sr.roleId,
    			sr.roleDesc
    			FROM
    			sys_user su
    			LEFT JOIN sys_user_role sur ON su.userId = sur.userId
    			left join sys_role sr on sur.roleId=sr.roleId
    			WHERE
    			su.userId = $userSelf[userCenterUserId]
    			limit 0,1
    			";
    			$centerUserInfo = $mysqlTools->selectSql($queryMyGlodSql)[0];
    			$surGlod = $centerUserInfo['userGold']+500;
    			$centerUserMoSql = "
    			insert into user_bop_info(userInFId,userInFUserId,userInFLoginId,userInFCreatetime,
    					userInFType,userInFMo,roleId,roleDesc,userInFOthMo,userInFReason,sysProInId,userInFSurGlod,userInFZf) values
    					($userInFId,$userSelf[userCenterUserId],'$userSelf[userCenterLoginId]',now(),4,500,$centerUserInfo[roleId],
    					'$centerUserInfo[roleDesc]'
    					,0,4,$sysProInId,$surGlod,1)
    					";
    			$mysqlTools->executeSql($centerUserMoSql);
    			 
    			$addCenterUserMoSql = "
    			update sys_user set userGold=userGold+500 where userId=$userSelf[userCenterUserId]
    			";
    			$mysqlTools->executeSql($addCenterUserMoSql);
    			$accuMo = $accuMo+500;
    		}
    		
    		//为指定收益人给予系统指定的提成
    		//查询出收益人userId
    		$queryIncomeUserId = "
    			select sysBenUserId from sys_set limit 0,1
    		";
    		$incomeUserId = $mysqlTools->selectSql($queryIncomeUserId)[0]['sysBenUserId'];
    		$accuMo = $accuMo + $this->userBonus($incomeUserId, 5, 10000, 5,$sysProInId);
    		
    		$sysProInMo = 10000-$accuMo;
    		
    		//拿出10%给前10级推荐人
    		//查询关联的10个用户信息
    		$lossMo = $this->tenRecomUserOnePercent($userId, 100, $sysProInId);
    	    $sysProInMo = $sysProInMo-$lossMo;
    		
    		$sysIncomeLogSql = "
    			insert into sys_profit_info (sysProInId,sysProInCreatetime,sysProInReason,sysProInMo)
    			values ($sysProInId,now(),2,$sysProInMo);
    		";
    		$mysqlTools->executeSql($sysIncomeLogSql);
    		
    		$result=true;
    		if($result){
    			$mysqlTools->commitTransaction();
    		}else{
    			$mysqlTools->rollback();
    		}
    	} catch (\Exception $e) {
    		$mysqlTools->rollback();
    		return $result;
    	}
    	return $result;
    }
    
    /**
     * 财务把一个普通会员升级为报单用户
     */
    public function updateMemToCenter($condition)
    {
    	global $mysqlTools;
    	try {
    		tsLoad('/manage/busi/UserBusi.class.php');
    		$mysqlTools->startTransaction();
    		$userId = $condition['userId'];
    		$condition = $mysqlTools->check_input($condition);
    	
    		//把一个用户改成激活状态变成了普通会员
    		$coreSql = "
    		update sys_user set userIsCenterUser=1 where userId = $condition[userId]
    		";
    		$mysqlTools->executeSql($coreSql);
    	
    		//查询用户分层情况
    		$queryUser = "
    		SELECT
    		su.userId,
    		su.userLoginId,
    		su.userPwd,
    		su.userPhone,
    		su.userTel,
    		su.userEmail,
    		su.userQQ,
    		su.userAvatarId,
    		su.userState,
    		su.userShortIndex,
    		su.userIndex,
    		su.userCreateTime,
    		su.userSex,
    		su.userPassTime,
    		su.userRecom1UserId,
    		su.userRecom1LoginId,
    		su.userRecom2UserId,
    		su.userRecom2LoginId,
    		su.userRecom3UserId,
    		su.userRecom3LoginId,
    		su.userIsCenterUser,
    		su.userPassType,
    		su.userGold,
    		su.userMainPassUserId,
    		su.userMainPassLoginId,
    		su.userCenterUserId,
    		su.userCenterLoginId
    		from
    		sys_user su
    		where
    		su.userId = $condition[userId]
    		";
    		//取出1，2，3级推荐人
    		$userSelf = $mysqlTools->selectSql($queryUser)[0];
    		//划分累积的奖金
    		$accuMo = 0;
    		//系统收益ID要提前生成起以便于关联查询
    		$sysProInId = getCurrentId();
    		if(isset($userSelf)){
	    		$userRecom1UserId = $userSelf['userRecom1UserId'];
	    		$userRecom2UserId = $userSelf['userRecom2UserId'];
	    		$userRecom3UserId = $userSelf['userRecom3UserId'];
	    		//根据用户角色计算用户获得奖金
	    		if(isset($userRecom1UserId))
	    			$accuMo = $accuMo + $this->userBonus($userRecom1UserId, 1, 9000, 1,$sysProInId);
	    		if(isset($userRecom2UserId))
	    	    	$accuMo = $accuMo + $this->userBonus($userRecom2UserId, 2, 9000, 1,$sysProInId);
	    	    if(isset($userRecom3UserId))
	    	    	$accuMo = $accuMo + $this->userBonus($userRecom3UserId, 3, 9000, 1,$sysProInId);
	    	}
	    	//为系统记录收入日志
	    	$userInFId = getCurrentId();
	    	//查看是否有报单用户,有报单用户将多获得500元的现金
	    	if(isset($userSelf['userCenterUserId'])){
	    		//计算操作后我的野猪币数量为
	    		$queryMyGlodSql = "
	    		SELECT
	    		su.userGold,
	    		sr.roleId,
	    		sr.roleDesc
	    		FROM
	    		sys_user su
	    		LEFT JOIN sys_user_role sur ON su.userId = sur.userId
	    		left join sys_role sr on sur.roleId=sr.roleId
	    		WHERE
	    		su.userId = $userSelf[userCenterUserId]
	    		limit 0,1
	    		";
	    		$centerUserInfo = $mysqlTools->selectSql($queryMyGlodSql)[0];
	    		$surGlod = $centerUserInfo['userGold']+450;
	    		$centerUserMoSql = "
	    		insert into user_bop_info(userInFId,userInFUserId,userInFLoginId,userInFCreatetime,
	    		userInFType,userInFMo,roleId,roleDesc,userInFOthMo,userInFReason,sysProInId,userInFSurGlod,userInFZf) values
	    		($userInFId,$userSelf[userCenterUserId],'$userSelf[userCenterLoginId]',now(),4,450,$centerUserInfo[roleId],
	    		'$centerUserInfo[roleDesc]'
	    		,0,4,$sysProInId,$surGlod,1)
	    		";
	    		$mysqlTools->executeSql($centerUserMoSql);
	    	
	    		$addCenterUserMoSql = "
	    		update sys_user set userGold=userGold+450 where userId=$userSelf[userCenterUserId]
	    		";
	    		$mysqlTools->executeSql($addCenterUserMoSql);
	    		$accuMo = $accuMo+450;
	    	}
    	    
    	    //为指定收益人给予系统指定的提成
    	    //查询出收益人userId
    	    $queryIncomeUserId = "
    			select sysBenUserId from sys_set limit 0,1
    		";
    	    $incomeUserId = $mysqlTools->selectSql($queryIncomeUserId)[0]['sysBenUserId'];
    	    $accuMo = $accuMo + $this->userBonus($incomeUserId, 5, 9000, 5,$sysProInId);
    	
    	    $sysProInMo = 9000-$accuMo;
    	    
    	    //拿出10%给前10级推荐人
    	    //查询关联的10个用户信息
    	    $lossMo = $this->tenRecomUserOnePercent($userId, 90, $sysProInId);
    	    $sysProInMo = $sysProInMo-$lossMo;
    	    
    	    $sysIncomeLogSql = "
    	    	insert into sys_profit_info (sysProInId,sysProInCreatetime,sysProInReason,sysProInMo)
    	    	values ($sysProInId,now(),3,$sysProInMo);
    	    ";
    	    $mysqlTools->executeSql($sysIncomeLogSql);
    	
    	    $result=true;
    	    if($result){
    	    	//$userBusi = new UserBusi();
    	    	//$userBusi->upgradeUserTree($userId);
    	    	$mysqlTools->commitTransaction();
    		}else{
    			$mysqlTools->rollback();
    		}
    	} catch (\Exception $e) {
    		$mysqlTools->rollback();
    		return $result;
    	}
    	return $result;
    }
    
    /**
     * 增加用户获得钱的记录
     */
    public function insertUserBopInfo($userInfo,$getMo,$sysProInId){
    	global $mysqlTools;
    	 
    	$tenUserInFId = getCurrentId();
    	//增加收支明细记录
    	$userBopInfoSql = "
    	insert into user_bop_info(userInFId,userInFZf,userInFUserId,userInFLoginId,userInFCreatetime,userInFType,
    	userInFMo,roleId,roleDesc,userInFOthMo,userInFReason,userInFReId,withdId,sysProInId,userInFSurGlod
    	) values(
    	$tenUserInFId,1,$userInfo[userId],'$userInfo[userLoginId]',now(),6,$getMo,$userInfo[roleId],
    	'$userInfo[roleDesc]',0,11,0,0,$sysProInId,$userInfo[userGold]+$getMo
    	)
    	";
    	$mysqlTools->executeSql($userBopInfoSql);
    }
    
    /**
     * 为10级内的用户增加1%的佣金
     */
    public function tenRecomUserOnePercent($userId,$getMo,$sysProInId){
    	global $mysqlTools;
    	tsLoad('/manage/busi/UserBusi.class.php');
    	$userBusi = new UserBusi();
    	$tenLevelUsers = $userBusi->findTenLevelUserByUserId($userId);
    	//总计消耗金额
    	$lossMo = 0;
    	
    	foreach ($tenLevelUsers as $i=>$tenLevelUser)
    	{
    		//为推荐的用户每人加入1%的收入
    		$recomSql = "
    		update sys_user set userGold=userGold+$getMo where userId = $tenLevelUser[userId]
    		";
    		$mysqlTools->executeSql($recomSql);
    		$tenUserInFId = getCurrentId();
    		//增加收支明细记录
    		$userBopInfoSql = "
    		insert into user_bop_info(userInFId,userInFZf,userInFUserId,userInFLoginId,userInFCreatetime,userInFType,
    		userInFMo,roleId,roleDesc,userInFOthMo,userInFReason,userInFReId,withdId,sysProInId,userInFSurGlod
    		) values(
    		$tenUserInFId,1,$tenLevelUser[userId],'$tenLevelUser[userLoginId]',now(),7,$getMo,$tenLevelUser[roleId],
    		'$tenLevelUser[roleDesc]',0,12,0,0,$sysProInId,$tenLevelUser[userGold]+$getMo
    		)
    		";
    		$mysqlTools->executeSql($userBopInfoSql);
    		
    		$lossMo = $lossMo+$getMo;
    	}
    	return $lossMo;
    }
}	

?>